package com.ddtech.platform;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author leon
 *
 */
public class DIClient extends AbstractClient {
//	private static final String PROTOCOL_HTTP = "http";
//	private static final String PROTOCOL_HTTPS = "https";
	
	public static final short IMPORT_DATA_FILE_TYPE_EXCEL = 0;

	private static final String POINT_IMPORT = "/{id}/import";
	

	
	/**
	 * 
	 * @param serverUrl
	 */
	public DIClient(String serverUrl){
		super(serverUrl);
	}
	
	/**
	 * 跑表达式组
	 * @param groupId 表达式组id
	 * @param fileFolderPath 包含所有表达式用到的excel文件的目录
	 * @throws IOException 
	 */
	public void runImportGroup(String groupId, String fileFolderPath,Map<String,String> extraValues,short dataFileType) throws ClientException {
		
		File zipFile = null;
				
		try {
			zipFile = Zipper.pack(new File(fileFolderPath),getFilePostfixs(dataFileType));
			String endPoint = getEndPointUrl(POINT_IMPORT);
			HttpResponse<JsonNode> ret = Unirest.post(endPoint)
//										.header("Content-Type", "application/json")
										.routeParam("id", groupId)
										.field("requestParams", toJson(extraValues))
										.field("file", zipFile)
										.asJson();
			int status = ret.getStatus();
			if(status!=200){
				String message = ret.getBody().getObject().getString("message");
				throw new RuntimeException("执行导入失败.返回码："+status+" 出错原因:"+message);
			}
		} catch (UnirestException | IOException | JSONException e) {
			throw new ClientException("出错拉。",e);
		}finally{
			if(zipFile!=null){
				zipFile.delete();
			}
		}
	}
	
	private List<String> getFilePostfixs(short type){
		List<String> ret = new ArrayList<String>();
		if(IMPORT_DATA_FILE_TYPE_EXCEL == type){
			ret.add("xls");
			ret.add("xlsx");
		}

		return ret;
	}
	
	
	
	

	
}
